<template>
  <div class="outward-container">
    <!-- 查询 -->
    <div class="search-container">
      <el-input
          placeholder="请输入客户ID或姓名"
          style="width: 200px"
          v-model="queryKeyword"
          class="search-input"
          clearable
          @keyup.enter="fetchOutwardData"
      ></el-input>
      <el-button
          @click="fetchOutwardData"
          type="success"
          plain
          class="search-button"
          :loading="loading"
      >
        查询
      </el-button>
      <el-button
          @click="showOutwardDialog"
          type="primary"
          plain
          class="add-button"
      >
        新增
      </el-button>
    </div>

    <!-- 外出登记表格 -->
    <el-table
        :data="outwardList"
        class="outward-table"
        header-cell-class-name="table-header"
        v-loading="loading"
        empty-text="暂无数据"
    >
      <el-table-column
          label="序号"
          type="index"
          width="60px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="customerName"
          label="客户姓名"
          width="120px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="customerId"
          label="客户ID"
          width="120px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="outgoingreason"
          label="外出事由"
          width="120px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="outgoingtime"
          label="外出时间"
          width="120px"
          align="center"
          :formatter="formatDate"
      ></el-table-column>
      <el-table-column
          prop="expectedreturntime"
          label="回院时间"
          width="120px"
          align="center"
          :formatter="formatDate"
      ></el-table-column>
      <el-table-column
          prop="escorted"
          label="陪同人"
          width="100px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="escortedtel"
          label="陪同人电话"
          width="120px"
          align="center"
      ></el-table-column>
      <el-table-column label="操作" width="200px" align="center">
        <template #default="scope">
          <el-button
              type="primary"
              size="small"
              @click="showDetailDialog(scope.row.id)"
              class="detail-button"
          >
            查看
          </el-button>
          <el-button
              type="primary"
              size="small"
              @click="showEditDialog(scope.row.id)"
              class="edit-button"
          >
           更改回院时间
          </el-button>
<!--          <el-button-->
<!--              type="danger"-->
<!--              size="small"-->
<!--              @click="confirmDelete(scope.row.id)"-->
<!--              class="delete-button"-->
<!--          >-->
<!--            删除-->
<!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          background
          v-model:current-page="pageContains.pageNum"
          v-model:page-size="pageContains.pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageContains.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          class="pagination"
          :disabled="loading"
      />
    </div>

    <!-- 外出登记对话框 -->
    <el-dialog
        v-model="outwardDialog"
        :title="dialogTitle"
        class="outward-dialog"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-form :model="curOutward" class="outward-form" :rules="rules" ref="outwardForm">
        <el-form-item label="客户ID" prop="customerId" class="form-item">
          <el-input
              placeholder="输入客户ID"
              v-model="curOutward.customerId"
              class="form-input"
              clearable
              :disabled="dialogOptType === 2 || dialogOptType === 3"
          ></el-input>
        </el-form-item>
        <el-form-item label="外出事由" prop="outgoingreason" class="form-item">
          <el-input v-model="curOutward.outgoingreason" class="form-input" placeholder="请输入外出事由" :disabled="dialogOptType === 2 || dialogOptType === 3"></el-input>
        </el-form-item>
        <el-form-item label="外出时间" prop="outgoingtime" class="form-item">
          <el-date-picker
              v-model="curOutward.outgoingtime"
              class="form-date-picker"
              placeholder="选择外出时间"
              :disabled="dialogOptType === 2 || dialogOptType === 3"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="回院时间" prop="expectedreturntime" class="form-item">
          <el-date-picker
              v-model="curOutward.expectedreturntime"
              class="form-date-picker"
              placeholder="选择回院时间"
              :disabled="dialogOptType === 3"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="陪同人" prop="escorted" class="form-item">
          <el-input v-model="curOutward.escorted" class="form-input" placeholder="请输入陪同人" :disabled="dialogOptType === 2 || dialogOptType === 3"></el-input>
        </el-form-item>
        <el-form-item label="陪同人电话" prop="escortedtel" class="form-item">
          <el-input v-model="curOutward.escortedtel" class="form-input" placeholder="请输入陪同人电话" :disabled="dialogOptType === 2 || dialogOptType === 3"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="closeDialog" class="dialog-button">取消</el-button>
        <el-button type="primary" @click="confirmOpt" class="dialog-button" :loading="submitting" v-if="dialogOptType !== 3">{{ buttonOpt }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import http from '@/axios/http';
import qs from "qs";
import { ElMessage, ElMessageBox } from 'element-plus';

// 外出登记数据集合
let outwardList = ref([]);
// 搜索关键字
let queryKeyword = ref("");
// 对话框相关
let outwardDialog = ref(false);
let curOutward = ref({
  customerId: null,
  outgoingreason: '',
  outgoingtime: null,
  expectedreturntime: null,
  escorted: '',
  escortedtel: ''
});
let dialogTitle = ref("");
let buttonOpt = ref("");
let dialogOptType = ref(1); // 1:新增 2:编辑 3:查看
// 分页信息
let pageContains = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});
// 加载状态
let loading = ref(false);
// 提交状态
let submitting = ref(false);
// 表单验证
const outwardForm = ref(null);
const rules = reactive({
  customerId: [
    { required: true, message: '客户ID不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入数字ID', trigger: 'blur' }
  ],
  outgoingreason: [
    { required: true, message: '请输入外出事由', trigger: 'blur' }
  ],
  outgoingtime: [
    { required: true, message: '请选择外出时间', trigger: 'blur' }
  ],
  expectedreturntime: [
    { required: true, message: '请选择预计回院时间', trigger: 'blur' }
  ]
});

// 时间格式化函数，仅显示日期
const formatDate = (row, column, cellValue) => {
  if (cellValue) {
    const date = new Date(cellValue);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
  return '';
};

// 查询外出登记记录
function fetchOutwardData() {
  loading.value = true;

  let params = {
    pageNum: pageContains.value.pageNum,
    pageSize: pageContains.value.pageSize,
    keyword: queryKeyword.value.trim()
  };

  http.post('/lyy/get_all_outward', qs.stringify(params))
      .then(res => {
        if (res.data.result === 'success') {
          pageContains.value = res.data.data;
          outwardList.value = res.data.data.list;
        } else {
          ElMessage.error(res.data.error || "查询失败");
        }
      })
      .catch(error => {
        ElMessage.error('网络请求出错，请稍后重试');
        console.error('查询出错:', error);
      })
      .finally(() => {
        loading.value = false;
      });
}

// 显示新增对话框
function showOutwardDialog() {
  dialogTitle.value = "新增外出登记";
  buttonOpt.value = "新增";
  dialogOptType.value = 1;
  curOutward.value = {
    customerId: null,
    outgoingreason: '',
    outgoingtime: null,
    expectedreturntime: null,
    escorted: '',
    escortedtel: ''
  };
  outwardDialog.value = true;
  if (outwardForm.value) {
    outwardForm.value.resetFields();
  }
}

// 显示编辑对话框
function showEditDialog(id) {
  dialogTitle.value = "修改回院时间";
  buttonOpt.value = "确定";
  dialogOptType.value = 2;

  http.post('/lyy/get_outward_by_id', qs.stringify({ id: id }))
      .then(res => {
        if (res.data.result === 'success') {
          curOutward.value = res.data.data;
          outwardDialog.value = true;
        } else {
          ElMessage.error(res.data.error || '获取详细信息失败');
        }
      })
      .catch(error => {
        ElMessage.error('网络请求出错，请稍后重试');
        console.error('获取详细信息出错:', error);
      });
}

// 显示详细信息对话框
function showDetailDialog(id) {
  http.post('/lyy/get_outward_by_id', qs.stringify({ id: id }))
      .then(res => {
        if (res.data.result === 'success') {
          curOutward.value = res.data.data;
          dialogTitle.value = "查看外出登记详情";
          buttonOpt.value = "关闭";
          dialogOptType.value = 3; // 3: 查看
          outwardDialog.value = true;
        } else {
          ElMessage.error(res.data.error || '获取详细信息失败');
        }
      })
      .catch(error => {
        ElMessage.error('网络请求出错，请稍后重试');
        console.error('获取详细信息出错:', error);
      });
}

// 确认操作
function confirmOpt() {
  if (dialogOptType.value === 2) {
    // 仅验证预计回院时间
    outwardForm.value.validateField('expectedreturntime', (valid) => {
      if (!valid) {
        ElMessage.warning('请选择预计回院时间');
        return;
      }
      updateOutward();
    });
  } else if (dialogOptType.value === 1) {
    outwardForm.value.validate((valid) => {
      if (!valid) {
        ElMessage.warning('请填写完整信息');
        return;
      }
      addOutward();
    });
  }
}

// 新增外出登记
function addOutward() {
  submitting.value = true;

  let param = {
    customerId: curOutward.value.customerId,
    outgoingreason: curOutward.value.outgoingreason,
    outgoingtime: curOutward.value.outgoingtime,
    expectedreturntime: curOutward.value.expectedreturntime,
    escorted: curOutward.value.escorted,
    escortedtel: curOutward.value.escortedtel
  };

  http.post('/lyy/add_one_outward', param)
      .then(res => {
        if (res.data.result === 'success') {
          ElMessage.success('新增成功');
          closeDialog();
          fetchOutwardData();
        } else {
          ElMessage.error(res.data.error || '新增失败');
        }
      })
      .catch(error => {
        ElMessage.error('网络请求出错，请稍后重试');
        console.error('新增外出登记出错:', error);
      })
      .finally(() => {
        submitting.value = false;
      });
}

// 修改外出登记
function updateOutward() {
  submitting.value = true;

  let param = {
    id: curOutward.value.id,
    expectedreturntime: curOutward.value.expectedreturntime
  };

  http.post('/lyy/modify_outward_by_id', param)
      .then(res => {
        if (res.data.result === 'success') {
          ElMessage.success('修改成功');
          closeDialog();
          fetchOutwardData();
        } else {
          ElMessage.error(res.data.error || '修改失败');
        }
      })
      .catch(error => {
        ElMessage.error('网络请求出错，请稍后重试');
        console.error('修改外出登记出错:', error);
      })
      .finally(() => {
        submitting.value = false;
      });
}

// 确认删除
function confirmDelete(id) {
  ElMessageBox.confirm('确定要删除此外外登记记录吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonTitle: '取消',
    type: 'error'
  }).then(() => {
    removeOne(id);
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

// 删除操作
function removeOne(id) {
  loading.value = true;

  http.post('/lyy/remove_outward_by_id', qs.stringify({ id: id }))
      .then(res => {
        if (res.data.result === 'success') {
          ElMessage.success('删除成功');
          fetchOutwardData();
        } else {
          ElMessage.error(res.data.error || '删除失败');
        }
      })
      .catch(error => {
        ElMessage.error('网络请求出错，请稍后重试');
        console.error('删除操作出错:', error);
      })
      .finally(() => {
        loading.value = false;
      });
}

// 关闭对话框
function closeDialog() {
  outwardDialog.value = false;
  curOutward.value = {};
  if (outwardForm.value) {
    outwardForm.value.resetFields();
  }
}

// 分页处理
const handlePageChange = (pageNum) => {
  pageContains.value.pageNum = pageNum;
  fetchOutwardData();
};

const handleSizeChange = (pageSize) => {
  pageContains.value.pageSize = pageSize;
  fetchOutwardData();
};

// 初始化加载
onMounted(() => {
  fetchOutwardData();
});
</script>

<style scoped>
.outward-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  margin-right: 10px;
  width: 200px;
}

.search-button {
  margin-right: 10px;
}

.add-button {
  margin-left: 10px;
}

.outward-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.table-header {
  background-color: #f0f2f5;
  font-weight: bold;
  color: #333;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.pagination {
  width: 100%;
}

.outward-dialog {
  width: 500px;
}

.outward-form {
  width: 100%;
}

.form-item {
  margin-bottom: 22px;
}

.form-input,
.form-date-picker {
  width: 100%;
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;
}

.dialog-button {
  width: 45%;
  padding: 10px;
  margin: 0 5px;
}

.detail-button {
  margin-right: 10px;
}
</style>